package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.springmvc.LeaseException;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.model.enums.LeaseStatus;
import com.atguigu.lease.web.admin.mapper.RoomInfoMapper;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.atguigu.lease.web.admin.vo.room.RoomDetailVo;
import com.atguigu.lease.web.admin.vo.room.RoomItemVo;
import com.atguigu.lease.web.admin.vo.room.RoomQueryVo;
import com.atguigu.lease.web.admin.vo.room.RoomSubmitVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.catalina.webresources.war.WarURLConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【room_info(房间信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class RoomInfoServiceImpl extends ServiceImpl<RoomInfoMapper, RoomInfo>
        implements RoomInfoService {
    @Autowired
    private RoomInfoMapper roomInfoMapper;
    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private RoomFacilityService roomFacilityService;
    @Autowired
    private RoomLabelService roomLabelService;
    @Autowired
    private RoomAttrValueService roomAttrValueService;
    @Autowired
    private RoomLeaseTermService roomLeaseTermService;
    @Autowired
    private RoomPaymentTypeService roomPaymentTypeService;
    @Autowired
    private LeaseAgreementService leaseAgreementService;
    @Override
    public void customPage(IPage<RoomItemVo> page, RoomQueryVo queryVo) {
        roomInfoMapper.customPageSelect(page, queryVo);
    }

    @Override
    public void customSaveOrUpdate(RoomSubmitVo roomSubmitVo) {
        //1. 判断是保存还是更新 （mybatis-plus自动给我们主键回显）
        boolean isipdate=roomSubmitVo.getId()!=null;
        //2.调用保存更新方法
        saveOrUpdate(roomSubmitVo);
        //3. 如果是更新，根据公寓id删除中间表 6个表
        if(isipdate){
            //删除图片信息，考虑图片类型，删除公寓的图片
            LambdaQueryWrapper<GraphInfo> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            //图片类型作为条件，确保删除的是房间图片
            lambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.ROOM);
            //删除这个房间的图片
            lambdaQueryWrapper.eq(GraphInfo::getItemId,roomSubmitVo.getId());
            graphInfoService.remove(lambdaQueryWrapper);
            //删除房间-配套关系
            LambdaQueryWrapper<RoomFacility> roomFacilitylambdaQueryWrapper=new LambdaQueryWrapper<>();
            roomFacilitylambdaQueryWrapper.eq(RoomFacility::getRoomId,roomSubmitVo.getId());
            roomFacilityService.remove(roomFacilitylambdaQueryWrapper);
            //删除房间-标签信息
            LambdaQueryWrapper<RoomLabel> roomLabellambdaQueryWrapper=new LambdaQueryWrapper<>();
            roomLabellambdaQueryWrapper.eq(RoomLabel::getRoomId,roomSubmitVo.getId());
            roomLabelService.remove(roomLabellambdaQueryWrapper);
            //删除房间-属性值关系
            LambdaQueryWrapper<RoomAttrValue> roomAttrValuelambdaQueryWrapper=new LambdaQueryWrapper<>();
            roomAttrValuelambdaQueryWrapper.eq(RoomAttrValue::getRoomId,roomSubmitVo.getId());
            roomAttrValueService.remove(roomAttrValuelambdaQueryWrapper);
            //删除房间-租期关系
            LambdaQueryWrapper<RoomLeaseTerm> roomLeaseTermlambdaQueryWrapper=new LambdaQueryWrapper<>();
            roomLeaseTermlambdaQueryWrapper.eq(RoomLeaseTerm::getRoomId,roomSubmitVo.getId());
            roomAttrValueService.remove(roomAttrValuelambdaQueryWrapper);
            //删除房间-支付方式关系
            LambdaQueryWrapper<RoomPaymentType> paymentTypeLambdaQueryWrapper=new LambdaQueryWrapper<>();
            paymentTypeLambdaQueryWrapper.eq(RoomPaymentType::getRoomId,roomSubmitVo.getId());
            roomPaymentTypeService.remove(paymentTypeLambdaQueryWrapper);
        }
        //4. 进行中间表的保存动作,最终一定要重新插入中间表的关联数据,注意：图片类型本次固定是房间
        //图片的保存
        List<GraphVo> graphVoList = roomSubmitVo.getGraphVoList();
        //graphVoList不为空，也就是有图片
        if(!CollectionUtils.isEmpty(graphVoList)){
            ArrayList<GraphInfo> graphInfoList = new ArrayList<>(graphVoList.size());
            for (GraphVo graphVo : graphVoList) {
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setName(graphVo.getName());
                graphInfo.setItemType(ItemType.ROOM);
                graphInfo.setItemId(roomSubmitVo.getId());
                graphInfo.setUrl(graphVo.getUrl());
                graphInfoList.add(graphInfo);
            }
            graphInfoService.saveBatch(graphInfoList);
        }
        //房间-配套关系的保存
        List<Long> facilityInfoIds = roomSubmitVo.getFacilityInfoIds();
        //不为空说明有属性
        if(!CollectionUtils.isEmpty(facilityInfoIds)){
            ArrayList<RoomFacility> roomFacilityList = new ArrayList<>(facilityInfoIds.size());
            for (Long facilityInfoId : facilityInfoIds) {
                RoomFacility roomFacility = RoomFacility.builder()
                        .roomId(roomSubmitVo.getId())
                        .facilityId(facilityInfoId).build();
                roomFacilityList.add(roomFacility);
            }
            roomFacilityService.saveBatch(roomFacilityList);
        }
        //房间-标签信息的保存
        List<Long> labelInfoIds = roomSubmitVo.getLabelInfoIds();
        if(!CollectionUtils.isEmpty(labelInfoIds)){
            ArrayList<RoomLabel> roomLabelList = new ArrayList<>(labelInfoIds.size());
            for (Long labelInfoId : labelInfoIds) {
                RoomLabel roomLabel = RoomLabel.builder()
                        .roomId(roomSubmitVo.getId())
                        .labelId(labelInfoId).build();
                roomLabelList.add(roomLabel);
            }
            roomLabelService.saveBatch(roomLabelList);
        }
        //房间-属性关系的保存
        List<Long> attrValueIds = roomSubmitVo.getAttrValueIds();
        if(!CollectionUtils.isEmpty(attrValueIds)){
            ArrayList<RoomAttrValue> roomAttrValueList = new ArrayList<>(attrValueIds.size());
            for (Long attrValueId : attrValueIds) {
                RoomAttrValue roomAttrValue = RoomAttrValue.builder()
                        .roomId(roomSubmitVo.getId())
                        .attrValueId(attrValueId).build();
                roomAttrValueList.add(roomAttrValue);
            }
            roomAttrValueService.saveBatch(roomAttrValueList);
        }
        //房间-租期关系的保存
        List<Long> leaseTermIds = roomSubmitVo.getLeaseTermIds();
        if(!CollectionUtils.isEmpty(leaseTermIds)){
            ArrayList<RoomLeaseTerm> roomLeaseTermList = new ArrayList<>(leaseTermIds.size());
            for (Long leaseTermId : leaseTermIds) {
                RoomLeaseTerm roomLeaseTerm = RoomLeaseTerm.builder()
                        .roomId(roomSubmitVo.getId())
                        .leaseTermId(leaseTermId).build();
                roomLeaseTermList.add(roomLeaseTerm);
            }
            roomLeaseTermService.saveBatch(roomLeaseTermList);
        }
        //房间-支付方式
        List<Long> paymentTypeIds = roomSubmitVo.getPaymentTypeIds();
        if(!CollectionUtils.isEmpty(leaseTermIds)){
            ArrayList<RoomPaymentType> roomPaymentTypeList = new ArrayList<>(paymentTypeIds.size());
            for (Long paymentTypeId : paymentTypeIds) {
                RoomPaymentType roomPaymentType = RoomPaymentType.builder()
                        .roomId(roomSubmitVo.getId())
                        .paymentTypeId(paymentTypeId).build();
                roomPaymentTypeList.add(roomPaymentType);
            }
            roomPaymentTypeService.saveBatch(roomPaymentTypeList);
        }
    }

    @Override
    public RoomDetailVo customGetById(Long id) {
        return roomInfoMapper.customSelect(id);
    }

    @Override
    public void customRemoveById(Long id) {
        //判断是否有租约（2 5 7）
        LambdaQueryWrapper<LeaseAgreement> leaseAgreementLambdaQueryWrapper=new LambdaQueryWrapper<>();
        leaseAgreementLambdaQueryWrapper.eq(LeaseAgreement::getRoomId,id)
                .in(LeaseAgreement::getStatus, LeaseStatus.SIGNED,LeaseStatus.WITHDRAWING,LeaseStatus.RENEWING);
        long count = leaseAgreementService.count(leaseAgreementLambdaQueryWrapper);
        //有，抛出异常 207
        if(count>0){
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR);
        }

        //没有则删除非核心子表
        //删除图片信息，考虑图片类型，删除公寓的图片
        LambdaQueryWrapper<GraphInfo> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        //图片类型作为条件，确保删除的是房间图片
        lambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.ROOM);
        //删除这个房间的图片
        lambdaQueryWrapper.eq(GraphInfo::getItemId,id);
        graphInfoService.remove(lambdaQueryWrapper);
        //删除房间-配套关系
        LambdaQueryWrapper<RoomFacility> roomFacilitylambdaQueryWrapper=new LambdaQueryWrapper<>();
        roomFacilitylambdaQueryWrapper.eq(RoomFacility::getRoomId,id);
        roomFacilityService.remove(roomFacilitylambdaQueryWrapper);
        //删除房间-标签信息
        LambdaQueryWrapper<RoomLabel> roomLabellambdaQueryWrapper=new LambdaQueryWrapper<>();
        roomLabellambdaQueryWrapper.eq(RoomLabel::getRoomId,id);
        roomLabelService.remove(roomLabellambdaQueryWrapper);
        //删除房间-属性值关系
        LambdaQueryWrapper<RoomAttrValue> roomAttrValuelambdaQueryWrapper=new LambdaQueryWrapper<>();
        roomAttrValuelambdaQueryWrapper.eq(RoomAttrValue::getRoomId,id);
        roomAttrValueService.remove(roomAttrValuelambdaQueryWrapper);
        //删除房间-租期关系
        LambdaQueryWrapper<RoomLeaseTerm> roomLeaseTermlambdaQueryWrapper=new LambdaQueryWrapper<>();
        roomLeaseTermlambdaQueryWrapper.eq(RoomLeaseTerm::getRoomId,id);
        roomAttrValueService.remove(roomAttrValuelambdaQueryWrapper);
        //删除房间-支付方式关系
        LambdaQueryWrapper<RoomPaymentType> paymentTypeLambdaQueryWrapper=new LambdaQueryWrapper<>();
        paymentTypeLambdaQueryWrapper.eq(RoomPaymentType::getRoomId,id);
        roomPaymentTypeService.remove(paymentTypeLambdaQueryWrapper);
        //删除房间表
        removeById(id);
    }
}




